<?php
// Copyright 2008 Datapolis Solutions OY
// 
// This file is part of a program, that is distributed
// under the terms of the GNU General Public License,
// see license.txt for details.

//
//	Datapolis Solutions Oy
//
defined( '_JEXEC' ) or die( 'Direct Access to this location is not allowed.' );

///////////////////////////////////////////////////////////////////////////////
// DEFINES

define('dpposition_PARAMS_SOURCE_MENU',      'menu');
define('dpposition_PARAMS_SOURCE_COMPONENT', 'component');

///////////////////////////////////////////////////////////////////////////////
// CONTROLLER

class dppositionBaseController {
	
	/** @var mosParameters Component's parameters. */
	var $_params;
	/** @var string Parameters source, dpposition_PARAMS_SOURCE_MENU or dpposition_PARAMS_SOURCE_COMPONENT. */
	var $_paramsSource;
	
	/** @var boolean True if frontend editor is allowed at all. */
	var $_frontendParamsEditor;
	/** @var array Array containing allowed usertypes. */
	var $_frontendParamsEditorUsertypes;
	
	/** @var object Joomla's mainframe object. */
	var $_mf;
	/** @var object Joomla's database object. */
	var $_db;
	/** @var object Joomla's current user. */
	var $_my;
	
	/** @var dppositionView Component's view object. */
	var $_view;
	
	/** @var string Current component (this component) */
	var $option;
	/** @var string Component's current task */
	var $task;
	/** @var integer Current Itemid (selected menu link) */
	var $Itemid;
	
	function dppositionBaseController ( &$mainframe, &$database, &$my, &$option, &$task, &$Itemid )
	{
		$this->_params = null;
		$this->_paramsSource = '';
		
		$this->_frontendParamsEditor = false;
		$this->_frontendParamsEditorUsertypes = array();
		
		$this->_mf =& $mainframe;
		$this->_db =& $database;
		$this->_my =& $my;
		
		$this->option = $option;
		$this->task   = $task;
		$this->Itemid = $Itemid;
		
		$this->_view = null;
	}
	
	function setView ( &$view )
	{
		$this->_view =& $view;
	}
	
	///////////////////////////////////////////////////////////////////////////
	// mosConfig
	
	/**
	* If $key isn't found $default is returned.
	* 
	* @param  string $key       Key
	* @param  string $default   (optional) [default ""] Default value
	* @return string
	*/
	function mosConf ( $key, $default='' )
	{
		if( substr($key, 0, 10) !== 'mosConfig_' ){
			$key = 'mosConfig_'.$key;
		}
		if( array_key_exists($key, $GLOBALS) ){
			return $GLOBALS[$key];
		}
		return $default;
	}
	
	///////////////////////////////////////////////////////////////////////////
	// PARAMETER EDITOR
	
	/**
	* True if frontend params editor access is allowed at all
	* 
	* @param  boolean $value
	* @return void
	*/
	function frontendParamsEditorAllowed ( $value )
	{
		$value = intval($value);
		if( $value > 0 ){
			$this->_frontendParamsEditor = true;
		}else{
			$this->_frontendParamsEditor = false;
		}
	}
	
	/**
	* Add usertype which is allowed to access frontend parameters editor
	* 
	* @param  string $usertype Usertype
	* @return boolean
	*/
	function addFrontendParamsEditorUsertype ( $usertype )
	{
		$this->_frontendParamsEditorUsertypes[] = strtolower($usertype);
		return true;
	}
	
	/**
	* Checks if frontend editor access is allowed for current user.
	* 
	* @return boolean False on error.
	*/
	function canAccessFrontendParamsEditor (  )
	{
		// _frontendParamsEditor
		if( $this->_frontendParamsEditor !== true ){
			return false;
		}
		
		// _frontendParamsEditorUsertypes
        if( !in_array(strtolower($this->_my->usertype), $this->_frontendParamsEditorUsertypes) 
			|| empty($this->_frontendParamsEditorUsertypes) ){
            return false;
        }
		
		return true;
	}
	
	function taskParamsEdit (  )
	{
		// check parameter editor access
		if( !$this->canAccessFrontendParamsEditor() ){
			mosRedirect(sefRelToAbs("index.php?option=".$this->option."&Itemid=".$this->Itemid), dpposition_FRONTEND_EDIT_DENIED);
			exit;
		}
		
		if( $this->task == "paramsEdit" ){
			$this->_view->taskParamsEdit( $this->option, $this->task, $this->Itemid, $this->_params );
		}else{
			$this->_view->taskParamsView( $this->option, $this->task, $this->Itemid, $this->_params );
		}
	}
	
	function paramsSave (  )
	{
		// check parameter editor access
		if( !$this->canAccessFrontendParamsEditor() ){
			mosRedirect(sefRelToAbs("index.php?option=".$this->option."&Itemid=".$this->Itemid), dpposition_FRONTEND_EDIT_DENIED);
			exit;
		}
		
		// save parameters
		$params = mosGetParam( $_POST, 'params', '' );
		$msg = dpposition_NO_PARAMS;
		if( !empty($params) ){
			if (is_array( $params )) {
				$txt = array();
				foreach ($params as $k=>$v) {
					if( get_magic_quotes_gpc() ){
						$v = stripslashes($v);
					}
					$txt[] = "$k=$v";
				}
				$params_txt = mosParameters::textareaHandling( $txt );
				$msg = dpposition_PARAMS_UNKNOWN_SOURCE;
				
				// menu
				if( $this->_paramsSource == dpposition_PARAMS_SOURCE_MENU )
				{
					$sql = "UPDATE #__menu SET 
						`params`=".$this->_db->Quote($params_txt)."
						WHERE 
							`id`=".$this->_db->Quote($this->Itemid)
							." AND `published`=1"
							." AND `type`='components'"
							." AND `link` LIKE ".$this->_db->Quote('%option=com_dpposition%')
							." LIMIT 1";
					$this->_db->setQuery( $sql );
					if( !$this->_db->query() ){
						$this->_errorHandler(__LINE__, $this->_db->stderr());
					}
					$msg = dpposition_PARAMS_SAVED;
				}
				
				// component
				if( $this->_paramsSource == dpposition_PARAMS_SOURCE_COMPONENT )
				{
					$sql = "UPDATE #__components SET 
						`params`=".$this->_db->Quote($params_txt)."
						WHERE 
							`option`=".$this->_db->Quote('com_dpposition')
							." AND `parent`=0"
							." LIMIT 1";
					$this->_db->setQuery( $sql );
					if( !$this->_db->query() ){
						$this->_errorHandler(__LINE__, $this->_db->stderr());
					}
					$msg = dpposition_PARAMS_SAVED;
				}
			}
		}
		
		mosRedirect(sefRelToAbs("index.php?option=".$this->option."&Itemid=".$this->Itemid."&task=paramsView"), $msg);
		exit;
	}
	
	///////////////////////////////////////////////////////////////////////////
	// OTHER METHODS
	
	/**
	* Load component's parameters from #__components table.
	* 
	* @param  boolean $menuParams (optional) [true] If true, try to load menu parameters.
	* @return boolean             False on failure
	*/
	function loadParameters ( $menuParams=true )
	{
		//oma: 
		return true;
		
		if( $this->_params === null )
		{
			// 1st try, menu parameters
			if( $menuParams === true )
			{
				$sql = "SELECT `params` 
					FROM #__menu 
					WHERE
						`id`=".$this->_db->Quote($this->Itemid)
						." AND `published`=1"
						." AND `type`='components'"
						." AND `link` LIKE ".$this->_db->Quote('%option=com_dpposition%')
						." LIMIT 1";
				$this->_db->setQuery( $sql );
				$params = $this->_db->loadResult();
				if( empty($params) === false ){
					$this->_paramsSource = dpposition_PARAMS_SOURCE_MENU;
					$this->_params =& new mosParameters($params, $this->_mf->getPath('com_xml', 'com_dpposition'), 'component');
					return true;
				}
			}
			
			// 2nd try, component parameters
			$sql = "SELECT `params` 
				FROM #__components 
				WHERE
					`option`=".$this->_db->Quote('com_dpposition')
					." AND `parent`=0"
					." LIMIT 1";
			$this->_db->setQuery( $sql );
			$params = $this->_db->loadResult();
			if( empty($params) === false ){
				$this->_paramsSource = dpposition_PARAMS_SOURCE_COMPONENT;
				$this->_params =& new mosParameters($params, $this->_mf->getPath('com_xml', 'com_dpposition'), 'component');
				return true;
			}
		}else if( is_object($this->_params) ){
			if( strtolower(get_class($this->_params)) == 'mosparameters' ){
				return true;
			}
		}
		return false;
	}
	
	function _errorHandler ( $line, $str, $exit=true )
	{
		$this->errorHandling('controller', $line, $str, $exit);
	}
	
	function errorHandling ( $source, $line, $str, $exit=true )
	{
		if( intval($this->_params->get('error_output', '0')) == 1 )
		{
			$error_output_ips = preg_replace('#[^0-9\.\,]#', '', $this->_params->get('error_output_ips', ''));
			$ips = explode(',', $error_output_ips);
			if( $error_output_ips == "" ){
				echo "dpposition error($source, line $line): $str";
			}else if( is_array($ips) ){
				if( in_array($_SERVER["REMOTE_ADDR"], $ips) ){
					echo "dpposition error($source, line $line): $str";
				}
			}
		}
		if( $exit ){
			exit;
		}
	}
}

///////////////////////////////////////////////////////////////////////////////
// VIEW

class dppositionBaseView {
	
	/** @var dppositionController Component's controller object. */
	var $_ctrl;
	
	function dppositionBaseView (  )
	{
		$this->_ctrl = null;
	}
	
	function setController ( &$controller )
	{
		$this->_ctrl =& $controller;
	}
	
	///////////////////////////////////////////////////////////////////////////
	// PARAMETER EDITOR
	
	function taskParamsView ( $option, $task, $Itemid, &$params )
    {
		$this->_ctrl->_mf->addCustomHeadTag('<link href="'.$this->_ctrl->mosConf('live_site').'/components/com_dpposition/css/params.css"'
			.' rel="stylesheet" type="text/css" />');
		$params->render();
		if( is_object($params->_xmlElem) ){
			echo '<div id="overDiv" style="position:absolute; visibility:hidden; z-index:10000;"></div>
			<table class="dpposition_p_header">
			<tr>
				<th>'.dpposition_HEADING.'</th>
				<td>
					<a href="'.sefRelToAbs("index.php?option=$option&Itemid=$Itemid&task=paramsEdit").'"><img border="0" align="middle" title="Edit" name="edit" alt="edit" src="'.$this->_ctrl->mosConf('live_site').'/administrator/images/edit_f2.png" /><br />Edit</a>
				</td>
			</tr>
			</table>
			
			<table class="dpposition_p_params">
			<tr><td><table width="100%" class="paramlist">';
			foreach ( $params->_xmlElem->childNodes as $param )
			{
				$html = array();
				
				$name = $param->getAttribute( 'name' );
				$label = $param->getAttribute( 'label' );
				$value = $params->get( $name, $param->getAttribute( 'default' ) );
				$description = $param->getAttribute( 'description' );
				$type = $param->getAttribute( 'type' );
				
				$html['name'] = $label ? $label : $name;
				
				// row start
				echo '<tr>';
				
				// name
				echo '<td width="40%" align="right" valign="top"><span class="editlinktip">';
				if ($html['name'] == '@spacer') {
					echo '&nbsp;';
				}else{
					echo mosToolTip( addslashes( $description ), addslashes( $html['name'] ), '', '', $html['name'], '#', 0 );
				}
				echo '</span></td>';
				
				// value
				echo '<td>';
				switch ($type)
				{
					case "list":
					case "radio":
						foreach ($param->childNodes as $option) {
							if( $option->getAttribute('value') == $value ){
								echo $option->gettext();
								break;
							}
						}
						break;
					
					case "text":
					case "textarea":
						echo str_replace("\n", "<br />", htmlspecialchars(str_replace("<br />", "\n", $value)));
						break;
					
					case "mos_section":
						$value_out = intval($value);
						if( $value_out > 0 ){
							$query = "SELECT `title`"
								. " FROM `#__sections`"
								. " WHERE "
								. " `scope` = 'content'"
								. " AND `id` = ".$this->_ctrl->_db->Quote( $value_out )
								;
							$this->_ctrl->_db->setQuery( $query );
							$value_out = $this->_ctrl->_db->loadResult();
							if( $value_out === null ){
								$value_out = 'Database Error!';
								//echo '<!-- '.$this->_ctrl->_db->stderr().' -->';
							}
						}else{
							$value_out = dpposition_MOS_SECTION_ZERO;
						}
						echo $value_out;
						break;
					
					case "mos_category":
						$value_out = intval($value);
						if( $value_out > 0 ){
							$query 	= "SELECT CONCAT_WS('/', s.`title`, c.`title`)"
								. " FROM `#__categories` AS c"
								. " LEFT JOIN `#__sections` AS s ON s.`id`=c.`section`"
								. " WHERE "
								. " s.`scope` = 'content'"
								. " AND c.`id` = ".$this->_ctrl->_db->Quote( $value_out )
								;
							$this->_ctrl->_db->setQuery( $query );
							$value_out = $this->_ctrl->_db->loadResult();
							if( $value_out === null ){
								$value_out = 'Database Error!';
								//echo '<!-- '.$this->_ctrl->_db->stderr().' -->';
							}
						}else{
							$value_out = dpposition_MOS_CATEGORY_ZERO;
						}
						echo $value_out;
						break;
					
					case "mos_menu":
						echo $value;
						break;
					
					case "imagelist":
						if( intval($value) == -1 ){
							echo dpposition_IMAGELIST_DO_NOT_USE;
						}else{
							echo $value;
						}
						break;
					
					case "spacer":
						echo '<hr />';
						break;
				}
				echo '</td>';
				
				// row end
				echo '</tr>';
			}
			echo '</table></td></tr></table>
			<script language="Javascript" src="'.$this->_ctrl->mosConf('live_site').'/includes/js/overlib_mini.js"></script>';
		}else{
			echo '<table class="dpposition_p_header">
			<tr>
				<th>'.dpposition_HEADING.'</th>
				<td>&nbsp;</td>
			</tr>
			</table>
			
			<table class="dpposition_p_params">
			<tr>
			<td>'.dpposition_NO_PARAMS.'</td>
			</tr>
			</table>';
		}
	}
	
	function taskParamsEdit ( $option, $task, $Itemid, &$params )
    {
		$this->_ctrl->_mf->addCustomHeadTag('<link href="'.$this->_ctrl->mosConf('live_site').'/components/com_dpposition/css/params.css"'
			.' rel="stylesheet" type="text/css" />');
		$paramshtml = $params->render();
		if( !is_object($params->_xmlElem) ){
			$paramshtml = NULL;
		}
		
		echo '<div id="overDiv" style="position:absolute; visibility:hidden; z-index:10000;"></div>
		<form id="dpposition_form" action="'.sefRelToAbs("index.php").'" method="post">
		<table class="dpposition_p_header">
		<tr>
			<th>'.dpposition_HEADING.'</th>
			<td>
				<a href="#" onClick="document.getElementById(\'dpposition_form\').submit();"><img border="0" align="middle" title="Save" name="save" alt="save" src="'.$this->_ctrl->mosConf('live_site').'/administrator/images/save_f2.png" /><br />Save</a>
				<a href="'.sefRelToAbs("index.php?option=$option&Itemid=$Itemid&task=paramsView").'"><img border="0" align="middle" title="Cancel" name="cancel" alt="cancel" src="'.$this->_ctrl->mosConf('live_site').'/administrator/images/cancel_f2.png" /><br />Cancel</a>
			</td>
		</tr>
		</table>
		
		<table class="dpposition_p_params">
		<tr>
		<td>'.(empty($paramshtml) ? dpposition_NO_PARAMS : $paramshtml).'</td>
		</tr>
		</table>
		
		<input type="hidden" name="option" value="'.$option.'" />
		<input type="hidden" name="task" value="paramsSave" />
		<input type="hidden" name="Itemid" value="'.$Itemid.'" />
		</form>
		<script language="Javascript" src="'.$this->_ctrl->mosConf('live_site').'/includes/js/overlib_mini.js"></script>';
	}
	
	///////////////////////////////////////////////////////////////////////////
	// OTHER METHODS
	
	function _errorHandler ( $line, $str, $exit=true )
	{
		$this->_ctrl->errorHandling('view', $line, $str, $exit);
	}
}
